package com.mc.lp.database.entity.helper;

import java.util.ArrayList;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.CollectionUtils;

import com.mc.lp.database.entity.PermissionEntity;
import com.mc.lp.database.entity.UserEntity;
import com.mc.lp.shared.vo.UserVO;
/**
 * entity helper for user entity
 * @author deepak
 *
 */
public class UserEntityHelper implements IEntityHelper<UserEntity, UserVO> {

	public UserEntity getEntity(UserVO vo) {
		return null;
	}
	
	/**
	 * this method will return the user vo but without authorities
	 */
	public UserVO getVO(UserEntity entity) {
		UserVO user = getVOWithAuthorities(entity, null);
		return user;
	}
	
	public UserVO getVO(UserEntity entity,  ArrayList<String> roles) {
		return getVOWithAuthorities(entity, roles);
	}
	
	/**
	 * return value object with authorities 
	 * @param entity
	 * @param roles
	 * @return
	 */
	public UserVO getVOWithAuthorities(UserEntity entity, ArrayList<String> roles){
		//load permissions into granted authorities and then set it to user
		ArrayList<GrantedAuthority> autorities = new ArrayList<GrantedAuthority>();
		if(!CollectionUtils.isEmpty(roles))
		for(String role:roles){
			autorities.add(new SimpleGrantedAuthority(role));
		}
		
		UserVO user = new UserVO(entity.getUserName(), entity.getEncryptedPassword(), entity.isActive(), !entity.isCredentialsExpired(), !entity.isCredentialsExpired(), !entity.isLocked(),autorities);
		//set the single role id to the user.
		if(!CollectionUtils.isEmpty(entity.getRoles()))
			user.setRoleId(entity.getRoles().get(0).getId());//currently we are giving only role to user only.
		
		//setfirstname for time being
		user.setFirstName(entity.getUserName());
		user.setLastName("");
		user.setUserId(entity.getId());
		return user;
	}
	public ArrayList<String> getStringListFromPermissions(Set<PermissionEntity> permissions){
		ArrayList<String> permissionList = new ArrayList<String>();
		if(!CollectionUtils.isEmpty(permissions)){
			for(PermissionEntity permission:permissions){
				permissionList.add(permission.getPermissionName());
			}
		}
		return permissionList;
	}

	public void setEntity(UserVO vo, UserEntity entity) {
		
	}
}
